package client;

import java.io.*;
import java.net.*;
import java.util.*;

import msgs.*;
/**
 * Sender queue for PM. Just constantly sends messages
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 * @author Ryan Kortmann
 */
public class PMSender extends Thread implements TTConstants
{
	private static boolean go;
	protected static Vector<SimpleMsg> outQ;
	private int port;
	private String targetIP;
	
	private SimpleMsg msg;
	private ObjectOutputStream oos;
	
	private Socket socket;
	
	/**
	 * Constructs a sender queue on the requested port
	 * @param p port to use
	 */
    public PMSender(int p)
    {
		outQ = new Vector<SimpleMsg>();
		go = true;
		port = p;		
    }
    
    public void run()
    {
    	while(go)
    	{
    		// only parse if there's something there
    		if(!(outQ.isEmpty()))
    		{
    			msg = outQ.remove(0);
    			
    			try
    			{
    				String ip;
    					
    				//validity check for where we're sending
						if(!(msg.getFromIp().equals(TTClient.ip))) 
						{
							ip = msg.getFromIp();	// s/getIp/getFromIp
						}
						else
						{
							ip = msg.getIp();		// s/getFromIp/getIp
						}
						
	    				socket = new Socket(ip, port);
	    				oos = new ObjectOutputStream(socket.getOutputStream());
	    				oos.writeObject(msg);
						oos.flush();
						oos.close();
    			}
    			catch(Exception e)
    			{
    				e.printStackTrace();
    			}
    		}
    		else 
    		{
    			try { Thread.sleep(100);}
    			catch(Exception e) { e.printStackTrace(); }
    		}
    	}
    	
    	try {
			oos.close();
			socket.close();
		}
		catch(Exception e) {}
    }
    
    /**
     * Cleanly shuts down the pmsender
     */
    public static void killPMSender() {
		while (go) {
			if (outQ.isEmpty()) go = false;
			else try {
				Thread.sleep(10);
			} 
			catch (Exception e) {}
		}
	}
}